﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using Common.Logging;

using Spring.Context;
using Spring.Context.Support;

namespace BOSS.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 日志器
        /// </summary>
        private static readonly ILog logger = LogManager.GetLogger(typeof(MvcApplication));
        private static bool initialized = false;
        private static object syncObject = new object();

        public IList<IGlobalModule> GlobalModules { get; set; }
        public IList<ICustomModelBinder> ModelBinders { get; set; }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            logger.Info(string.Empty);
            logger.Info(new string('=', 40));
            logger.Info("系统启动....");

            logger.Info("注册路由映射");
            RegisterRoutes(RouteTable.Routes);

            logger.Info("初始化 Spring.Net");
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Context.Request.FilePath == "/")
            {
                Context.RewritePath("Default.aspx");
            }
        }

        protected void Application_End()
        {
            logger.Info(new string('=', 40));
            logger.Info("系统关闭....");
            logger.Info(string.Empty);
        }

        public override void Init()
        {
            base.Init();

            if (!initialized)
            {
                lock (syncObject)
                {
                    if (!initialized)
                    {
                        IApplicationContext appContext = ContextRegistry.GetContext();

                        appContext.ConfigureObject(this, "GlobalModuleInitializer");
                        appContext.ConfigureObject(this, "ModelBinderInitializer");

                        if (this.GlobalModules != null)
                        {
                            foreach (IGlobalModule module in this.GlobalModules)
                            {
                                logger.Info("初始化 " + module.Name);
                                try
                                {
                                    module.Initialize(this, appContext);

                                }
                                catch (Exception ex)
                                {
                                    logger.Warn(module.Name + "初始化异常", ex);
                                }
                            }
                        }

                        if (this.ModelBinders != null)
                        {
                            foreach (ICustomModelBinder modelBinder in this.ModelBinders)
                            {
                                foreach (Type type in modelBinder.SupportedTypes)
                                {
                                    logger.Info(string.Concat("注册模型绑定器：", type.Name, " - ", modelBinder.GetType().Name));
                                    System.Web.Mvc.ModelBinders.Binders.Add(type, modelBinder);
                                }
                            }
                        }

                        logger.Info("系统启动完成");
                        logger.Info(new string('=', 40));

                        initialized = true;
                    }
                }
            }
        }

        /// <summary>
        /// 判断当前是否处于 DEBUG 模式
        /// </summary>
        /// <returns></returns>
        public bool IsDebug
        {
            get
            {
#if DEBUG
                return true;
#else
                return false;
#endif
            }
        }
    }
}